package registry

import (
	"context"
	"encoding/json"
	"sen-golang-study/go_game_study/hero_story_go_server/common"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

// EtcdRegistry etcd服务注册器
type EtcdRegistry struct {
	client *clientv3.Client
}

// NewEtcdRegistry 创建etcd服务注册器
func NewEtcdRegistry(client *clientv3.Client) *EtcdRegistry {
	return &EtcdRegistry{
		client: client,
	}
}

// Register 注册服务信息
func (r *EtcdRegistry) Register(ctx context.Context, key string, serverInfo *common.GameServerInfo, ttl time.Duration) error {
	// 序列化服务信息
	marshalBytes, err := json.Marshal(serverInfo)
	if err != nil {
		log.Error("GameServerInfo序列化为JSON失败, %v", err)
		return err
	}

	// 创建租约
	grantResp, err := r.client.Grant(ctx, int64(ttl.Seconds()))
	if err != nil {
		log.Error("创建etcd租约失败, %v", err)
		return err
	}

	// 注册服务信息
	_, err = r.client.Put(ctx, key, string(marshalBytes), clientv3.WithLease(grantResp.ID))
	if err != nil {
		log.Error("注册服务信息到etcd失败, %v", err)
		return err
	}

	return nil
}

// Unregister 注销服务
func (r *EtcdRegistry) Unregister(ctx context.Context, key string) error {
	_, err := r.client.Delete(ctx, key)
	if err != nil {
		log.Error("从etcd删除服务信息失败, %v", err)
		return err
	}
	return nil
}

// Close 关闭etcd客户端
func (r *EtcdRegistry) Close() error {
	if r.client != nil {
		return r.client.Close()
	}
	return nil
}